<!-- 自定义长度的密码输入框 -->
<template>
  <div>
    <el-dialog :title="title" v-model="show" destroy-on-close :close-on-click-modal="false">
      <div class="verification-container">
        <input
          v-for="(code, index) in verificationCodes"
          :key="index"
          v-model="verificationCodes[index]"
          @input="handleInput(index, $event)"
          @keydown="handleKeyDown(index, $event)"
          :maxlength="inputLen"
          class="verification-input"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()

const props = defineProps({
  title: {
    type: String,
    default: '请输入密码',
  },
  inputLen: {
    type: Number,
    default: 6,
  },
})
// 是否展示
const show = ref(false)
const init = () => {
  show.value = true
}
// 子组件暴露方法
defineExpose({ init })

const emit = defineEmits(['comfirmPass'])

const verificationCodes = ref(new Array(props.inputLen).fill(''))

// 获取密码框中的字符
const handleInput = (index, event) => {
  const codeValue = event.target.value
  verificationCodes.value[index] = codeValue

  // 输入完毕
  if (verificationCodes.value.join('').length === props.inputLen) {
    emit('comfirmPass', verificationCodes.value.join(''))
    show.value = false
    verificationCodes.value = new Array(props.inputLen).fill('')
  }

  // 继续输入
  if (codeValue && index < verificationCodes.value.length - 1) {
    const nextInput = event.target.nextElementSibling
    if (nextInput) {
      nextTick(() => {
        nextInput.focus()
      })
    }
  }
}

const handleKeyDown = (index, event) => {
  // 处理删除操作
  if (event.key === 'Backspace' && !event.target.value && index > 0) {
    const prevInput = event.target.previousElementSibling
    if (prevInput) {
      nextTick(() => {
        prevInput.focus()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.verification-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.verification-input {
  width: 54px;
  height: 54px;
  margin-right: 30px;
  text-align: center;
  font-size: 20px;
  border: 1px solid #ebebeb;
  border-radius: 5px;
  &:last-child {
    margin-right: 0;
  }
}

.verification-input:focus {
  outline: none;
  // border-color: #007bff;
  // box-shadow: 0 0 5px #007bff;
}
</style>
